<template>
  <div class="container">
    <div class="tabber">
      <a-space size="medium" direction="vertical" fill>
        <a-space>
          <a-input placeholder="请输入标题搜索" v-model="search"></a-input>
          <a-button type="primary" @click="handleSearch">
            <template #icon>
              <icon-search />
            </template>
            <template #default>搜索</template>
          </a-button>
          <a-select
            @change="handleToggle"
            style="width: 80px"
            v-model="searchType"
          >
            <a-option value="title">标题</a-option>
            <a-option value="id">id</a-option>
          </a-select>
        </a-space>
        <a-space>
          <a-button
            type="primary"
            @click="
              visible = true;
              isAdd = true;
              form.type = 1;
              form.status = 1;
            "
          >
            <template #icon>
              <icon-plus />
            </template>
            <template #default>新增</template>
          </a-button>
          <a-button type="primary" @click="handleRefresh">
            <template #icon>
              <icon-loop />
            </template>
            <template #default>刷新</template>
          </a-button>
          <a-button
            status="danger"
            @click="deleteAll = selectedKeys.length > 0 ? true : false"
          >
            <template #icon>
              <icon-delete />
            </template>
            <template #default>批量删除</template>
          </a-button>
        </a-space>
      </a-space>
    </div>
    <a-table
      row-key="id"
      :columns="columns"
      :data="data"
      column-resizable
      :row-selection="rowSelection"
      v-model:selectedKeys="selectedKeys"
      :pagination="pagination"
      :bordered="{ cell: true }"
      :scroll="{ x: 'min-content' }"
      size="small"
      :table-layout-fixed="true"
    >
      <template #user="{ record }">
        {{ record.user }}
      </template>
      <template #cover="{ record }">
        <a-image
          fit="cover"
          width="64"
          height="64"
          :src="BASE_URL + record.cover"
        />
      </template>
      <template #covers="{ record }">
        <a-carousel
          :style="{
            width: '100px',
            height: '100px',
          }"
        >
          <a-carousel-item v-for="(image, index) in record.covers" :key="index">
            <img
              :src="BASE_URL + image"
              :style="{
                width: '100%',
                height: '100%',
                objectFit: 'cover',
              }"
            />
          </a-carousel-item>
        </a-carousel>
      </template>
      <template #details="{ record }">
        <a-carousel
          :style="{
            width: '100px',
            height: '100px',
          }"
          v-if="record.details.length > 0"
        >
          <a-carousel-item
            v-for="(image, index) in record.details"
            :key="index"
          >
            <img
              :src="BASE_URL+image"
              :style="{
                width: '100%',
                height: '100%',
                objectFit: 'cover',
              }"
            />
          </a-carousel-item>
         
        </a-carousel>
         <div v-else>暂无</div>
      </template>
      <template #optional="{ record }">
        <a-button
          size="mini"
          type="primary"
          style="margin-right: 5px"
          @click="editorHanddle(record)"
          >编辑</a-button
        >
        <a-button size="mini" status="danger" @click="deleteHanddle(record)"
          >删除</a-button
        >
      </template>
    </a-table>
  </div>
  <!-- 编辑弹框 -->
  <a-modal
    v-model:visible="visible"
    :title="isAdd ? '添加数据' : '修改数据'"
    @cancel="handleCancel"
    @before-ok="handleBeforeOk"
  >
    <!-- <a-typography-text type="secondary" style="margin-left: 10vh;margin-bottom: 10px;">id:{{ form.id
        }}</a-typography-text> -->
    <a-form :model="form" style="padding-right: 40px">
      <a-form-item label="ID" v-if="!isAdd">
        <a-input disabled v-model="form.id" />
      </a-form-item>
      <a-form-item label="标题">
        <a-input v-model="form.title" />
      </a-form-item>
      <a-form-item label="价格">
        <a-input-number
          v-model="form.price"
          :style="{ width: '180px' }"
          :precision="2"
          mode="button"
          size="large"
          class="input-demo"
        />
      </a-form-item>
      <a-form-item label="分类">
        <a-select v-model="form.classifyId" :style="{ width: '180px' }">
          <a-option
            v-for="item in storeClassify"
            :key="item.id"
            :value="item.id"
            >{{ item.name }}</a-option
          >
        </a-select>
      </a-form-item>

      <a-form-item label="封面">
        <a-upload
          v-if="visible"
          list-type="picture-card"
          :action="BASE_URL + '/api/upload'"
          :default-file-list="
            isAdd
              ? []
              : form.covers.map((item) => ({
                  uid: BASE_URL + item,
                  name: '20200717-103937.png',
                  url: BASE_URL + item,
                }))
          "
          @success="onUploadSuccess"
          @before-remove="beforeRemove"
          name="files"
          image-preview
          :limit="9"
        />
      </a-form-item>
      <a-form-item label="详情">
        <a-upload
          v-if="visible"
          list-type="picture-card"
          :action="BASE_URL + '/api/upload'"
          :default-file-list="
            isAdd
              ? []
              : form.details.map((item) => ({
                  uid: BASE_URL + item,
                  name: '20200717-103937.png',
                  url: BASE_URL + item,
                }))
          "
          @success="onUploadSuccessDetail"
          @before-remove="beforeRemoveDetail"
          name="files"
          image-preview
          :limit="9"
        />
      </a-form-item>
      <a-form-item label="描述">
        <a-textarea
          :auto-size="{ minRows: 6, maxRows: 8 }"
          placeholder="点击输入正文，您可在此交流骑行经验和生活，分享新鲜事"
          v-model="form.desc"
        />
      </a-form-item>
    </a-form>
  </a-modal>
  <!-- 删除弹框 -->
  <a-modal v-model:visible="delvalue" title="确认删除" @before-ok="delBeforeOk">
    <a-form :model="form">
      <a-form-item field="id" label="ID">
        <a-input disabled v-model="form.id" />
      </a-form-item>
      <a-form-item field="name" label="作者">
        <a-input disabled :placeholder="form.user?.nikeName" />
      </a-form-item>
    </a-form>
  </a-modal>
  <!-- 删除已选的 -->
  <a-modal v-model:visible="deleteAll" @before-ok="handleDeleteAll">
    <template #title> 警告 </template>
    <div>是否删除已选 {{ selectedKeys.length }} 项数据？</div>
  </a-modal>
</template>

<script setup>
import { BASE_URL } from "../../constant/index";
import { reactive, ref, onMounted } from "vue";
import {
  getStoreListApi,
  getStoreClassifyAllApi,
  postStoreApi,
  putStoreApi,
  deleteStoreApi,
} from "../../api/store.js";
import {
  IconPlus,
  IconSearch,
  IconLoop,
  IconDelete,
} from "@arco-design/web-vue/es/icon";

import { Message } from "@arco-design/web-vue";

const rowSelection = reactive({
  type: "checkbox",
  showCheckedAll: false,
  onlyCurrent: false,
});
const pagination = { pageSize: 10 };
const columns = [
  {
    title: "id",
    dataIndex: "id",
    fixed: "left",
    width: 150,
    ellipsis: true,
    tooltip: true,
    align: "center",
  },
  {
    title: "商品",
    dataIndex: "title",
    ellipsis: true,
    tooltip: true,
    width: 250,
    align: "center",
  },
  {
    title: "封面集",
    slotName: "covers",
    width: 132,
    align: "center",
  },
  {
    title: "价格",
    dataIndex: "price",
    width: 100,
    align: "center",
  },
  {
    title: "已售",
    dataIndex: "sale",
    width: 100,
    align: "center",
  },
  {
    title: "分类",
    dataIndex: "classify.name",
    width: 100,
    align: "center",
  },
  {
    title: "描述",
    dataIndex: "desc",
    ellipsis: true,
    tooltip: true,
    width: 250,
    align: "center",
  },

  {
    title: "图集",
    slotName: "details",
    width: 132,
    align: "center",
  },

  {
    title: "创建时间",
    dataIndex: "createdAt",
    width: 220,
    align: "center",
  },
  {
    title: "操作",
    fixed: "right",
    width: 200,
    slotName: "optional",
    align: "center",
  },
];

const data = ref([]);

const topicList = ref([]);

// 获取商品分类数据
const storeClassify = ref();

async function getStoreClassifyAll() {
  const getRes = await getStoreClassifyAllApi();
  console.log(getRes.data);
  if (getRes.code === 200) {
    storeClassify.value = getRes.data;
  }
}
getStoreClassifyAll();
// 获取用户数据
async function getListData() {
  const getRes = await getStoreListApi({
    limit: 1000,
    page: 1,
  });

  console.log(getRes.data.list);
  if (getRes.code === 200) {
    getRes.data.list.forEach((item) => {
      item.classifyId = item.classify.id;
    });
    data.value = getRes.data.list;
  }
}

// 获取用户数据
onMounted(() => {
  getListData();
});

//切换分类函数
async function handleToggle(type) {
  await getListData();
  if (type !== 0) {
    data.value = data.value.filter((item) => {
      return item.type === type;
    });
  }
}

// 点击刷新按钮
function handleRefresh() {
  data.value = [];
  getListData();
}
const deleteAll = ref(false);
// 已选择的数据
const selectedKeys = ref([]);
// 点击删除按钮
async function handleDeleteAll(done) {
  console.log(selectedKeys.value);
  const pra = selectedKeys.value.map((id) => {
    return new Promise(async (resolve, reject) => {
      const delRes = await deleteStoreApi({ id });
      console.log(delRes);
      if (delRes.code === 200) {
        resolve(delRes);
      } else {
        reject(delRes);
      }
    });
  });
  try {
    await Promise.all(pra);
    Message.success("批量删除成功");
    done();
    getListData();
  } catch (err) {
    Message.error("批量删除失败");
  }
  console.log("结束");

  return false;
}

const searchType = ref("title");
const search = ref("");
async function handleSearch() {
  await getListData();
  data.value = data.value.filter((item) => {
    return item[searchType.value].includes(search.value);
  });
}
// 上传图片回调
function onUploadSuccess(res) {
  console.log(res.response);
  if (res.response.code === 200) {
    const cover = res.response.data[0];
    if (form.value.covers == undefined) {
      form.value.covers = [];
    }
    form.value.covers.push(cover);
  }
}

// 删除图片验证
function beforeRemove(file) {
  console.log(file);
  form.value.covers = form.value.covers.filter(
    (item) => "http://127.0.0.1:3000" + item != file.url
  );

  console.log(form.value.covers);
  return true;
}
function onUploadSuccessDetail(res) {
  console.log(res.response);
  if (res.response.code === 200) {
    const cover = res.response.data[0];
    if (form.value.details == undefined) {
      form.value.details = [];
    }
    form.value.details.push(cover);
  }
}
function beforeRemoveDetail(file) {
  console.log(file);
  form.value.details = form.value.details.filter(
    (item) => "http://127.0.0.1:3000" + item != file.url
  );

  console.log(form.value.details);
  return true;
}

// 显示编辑弹框
const visible = ref(false);
const form = ref({});
const isAdd = ref(false);
// 取消弹框
function handleCancel() {
  isAdd.value = false;
  form.value = {};
}
// 点击编辑按钮
function editorHanddle(item) {
  console.log(item);
  form.value = JSON.parse(JSON.stringify(item));
  //   form.value = item;
  visible.value = true;
}
// 确认修改按钮
async function handleBeforeOk(done) {
  if (isAdd.value) {
    await handleAdd(done);
  } else {
    await handleUpdate(done);
  }
  // form.value = {};
  return false;
}
// 验证上传文件是否是视频
function beforeUpload(file) {
  return new Promise((resolve, reject) => {
    if (file.type.indexOf("video") === -1) {
      Message.error("上传文件必须为视频格式");
      reject(false);
    } else {
      resolve(true);
    }
  });
}
// 新增逻辑
async function handleAdd(done) {
  console.log(form.value);
  const {
    title,
    desc,
    price,
    covers = [],
    details = [],
    classifyId,
  } = form.value;
  if (!title) {
    Message.error("请输入标题");
    return false;
  }
  if (!desc) {
    Message.error("请输入正文");
    return false;
  }
  if (isNaN(Number(price)) || Number(price) <= 0) {
    Message.error("请输入正确价格");
    return false;
  }
  console.log(2);
  if (!classifyId) {
    Message.error("请选择分类");
    return false;
  }
  console.log(covers);
  if (covers.length <= 0) {
    Message.error("请上传封面集");
    return false;
  }

  const addRes = await postStoreApi({
    title,
    desc,
    price,
    covers,
    details,
    classifyId,
  });
  console.log(addRes);
  if (addRes.code === 200) {
    Message.success("新增成功");
    await getListData();

    done();
    form.value = {};
  } else {
    console.log(postRes);
    Message.error(postRes.message);
    return false;
  }
}
// 更新逻辑
async function handleUpdate(done) {
  const {
    id,
    title,
    desc,
    price,
    covers = [],
    details = [],
    classifyId,
  } = form.value;
  if (!id) {
    Message.error("请输入id");
    return false;
  }
  if (!title) {
    Message.error("请输入标题");
    return false;
  }
  if (!desc) {
    Message.error("请输入正文");
    return false;
  }
  if (isNaN(Number(price)) || Number(price) <= 0) {
    Message.error("请输入正确价格");
    return false;
  }
  console.log(2);
  if (!classifyId) {
    Message.error("请选择分类");
    return false;
  }
  console.log(covers);
  if (covers.length <= 0) {
    Message.error("请上传封面集");
    return false;
  }

  const putRes = await putStoreApi({
    id,
    title,
    desc,
    price,
    covers,
    details,
    classifyId,
  });
  console.log(putRes);
  if (putRes.code === 200) {
    Message.success("更新成功");
    await getListData();

    done();
    form.value = {};
  } else {
    console.log(postRes);
    Message.error(postRes.message);
    return false;
  }
}

// 删除弹框
const delvalue = ref(false);
// 点击删除按钮
function deleteHanddle(item) {
  console.log(item);
  form.value = JSON.parse(JSON.stringify(item));
  delvalue.value = true;
}
// 确认删除
async function delBeforeOk() {
  const { id } = form.value;
  console.log(id);
  const delRes = await deleteStoreApi({ id });
  console.log(delRes);
  if (delRes.code === 200) {
    Message.info("删除成功");
    // 更新数据
    getListData();
    delvalue.value = false;
  } else {
    Message.error("删除失败");
    return false;
  }
}
</script>

<style lang="less" scoped>
.container {
  padding: 14px;
  box-sizing: border-box;
  .tabber {
    padding-bottom: 14px;
  }
}
.container :deep(td) {
  // display: flex;
  // align-items: center;
  vertical-align: middle;
}
.topic-item {
  // background-color: red;
  padding: 4px 14px;
  // border-radius: 4px;
  &:hover {
    background-color: #f2f3f5;
    cursor: pointer;
  }
}
</style>
